package spark.sql

import org.apache.spark.SparkConf
import org.apache.spark.sql.{DataFrame, SaveMode, SparkSession}

/**
 * @Author Jeremy Zheng
 * @Date 2021/3/23 9:53
 * @Version 1.0
 * 读取mysql数据
 */
object SparkSQL04_JDBC_Demo1 {
  def main(args: Array[String]): Unit = {
    val conf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("toMySQLDemo")
    val spark: SparkSession = SparkSession.builder().config(conf).getOrCreate()
    import spark.implicits._

    //用load方法读取mysql数据
    val df: DataFrame = spark.read
      .format("jdbc")
      .option("url", "jdbc:mysql://hadoop101:3306/sparksql")
      .option("driver", "com.mysql.jdbc.Driver")
      .option("user", "root")
      .option("password", "123456")
      .option("dbtable", "user")
      .load()

    //df.show()

    //保存数据到mysql
    df.write
      .format("jdbc")
      .option("url", "jdbc:mysql://hadoop101:3306/sparksql")
      .option("driver", "com.mysql.jdbc.Driver")
      .option("user", "root")
      .option("password", "123456")
      .option("dbtable", "user1")
      .mode(SaveMode.Append)
      .save()
  }
}
